import 'dart:async';
import 'package:common_utils/common_utils.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter/animation.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:part_time_job_pro/common/index.dart';
import 'package:part_time_job_pro/common/mixins/user_mixin.dart';
import 'package:part_time_job_pro/pages/login/state.dart';

///登录逻辑
class LoginLogic extends BaseController with GetSingleTickerProviderStateMixin, UserMixin {
  final LoginState state = LoginState();

  //定时器
  Timer? _timer;
  late final AnimationController shakeController;

  ///输入监听
  late TextEditingController telTextEditController;
  late TextEditingController verifyPasswordTextFieldController;
  late TextEditingController passwordTextFieldController;
  late TextEditingController userNameTextEditController;

  ///监听是否正在输入数据
  late FocusNode telFocusNode;
  late FocusNode userNameFocusNode;
  late FocusNode verifyCodeFocusNode;
  late FocusNode passwordFocusNode;
  late FocusNode remeberMeFocusNode;

  //初始化
  @override
  void onInit() {
    telTextEditController = TextEditingController();
    verifyPasswordTextFieldController = TextEditingController();
    userNameTextEditController = TextEditingController();
    passwordTextFieldController = TextEditingController();

    telFocusNode = FocusNode();
    userNameFocusNode = FocusNode();
    verifyCodeFocusNode = FocusNode();
    passwordFocusNode = FocusNode();
    remeberMeFocusNode = FocusNode();

    //初始化动画
    shakeController = AnimationController(vsync: this, duration: const Duration(milliseconds: 500));
    shakeController.addListener(() {
      if (shakeController.status == AnimationStatus.completed) {
        shakeController.reset();
      }
    });

    initFocusNode();
    initRemeberChecked();
    super.onInit();
  }

  //注销函数
  @override
  void onClose() {
    telTextEditController.dispose();
    verifyPasswordTextFieldController.dispose();
    userNameTextEditController.dispose();
    passwordTextFieldController.dispose();
    shakeController.reset();
    shakeController.dispose();
    cancelTimer();
    super.onClose();
  }

  //晃动方法
  void shake() {
    shakeController.forward();
  }

  //初始化记住密码
  void initRemeberChecked() async {
    state.isRemeberMe = StorageService.to.getBool(STORAGE_REMEMBER_ME_KEY);
    LogUtil.e(state.isRemeberMe, tag: "记住密码缓存为:");
  }

  ///监听用户名称输入
  void updateUserName(String text) {
    state.userNameText = text;
    update();
  }

  ///监听密码输入
  void updatePassword(String text) {
    state.passwordText = text;
    update();
  }

  ///监听电话输入
  void updateTel(String text) {
    state.telText = text;
    update();
  }

  ///监听验证码输入
  void updateVerifyText(String text) {
    state.verifyText = text;
    update();
  }

  ///记住密码
  void updateRemeberMe() {
    state.isRemeberMe = !state.isRemeberMe;
    update();
  }

  //清空账号输入
  void clearUserName() {
    state.userNameText = '';
    userNameTextEditController.clear();
    userNameFocusNode.unfocus();
  }

  //清空密码输入
  void clearPassword() {
    state.passwordText = '';
    passwordTextFieldController.clear();
    passwordFocusNode.unfocus();
  }

  //清空验证码输入
  void clearVerifyCode() {
    state.verifyText = '';
    verifyPasswordTextFieldController.clear();
    verifyCodeFocusNode.unfocus();
  }

  ///是否同意协议
  void changeIsAgree() {
    state.isAgreement = !state.isAgreement;
    update();
  }

  //修改密码隐藏
  void updateIsObscure() {
    state.isObscure = !state.isObscure;
    update();
  }

  ///改变登录类型
  void changeLoginType() {
    state.loginTypeIsMessage = !state.loginTypeIsMessage;
    update();
  }

  ///监听是否在输入密码或验证码
  void initFocusNode() {
    verifyCodeFocusNode.addListener(() {
      if (verifyCodeFocusNode.hasFocus) {
        state.isInputPassword = true;
        update();
      } else {
        state.isInputPassword = false;
        update();
      }
    });
    telFocusNode.addListener(() {
      if (telFocusNode.hasFocus) {
        state.isInputPassword = false;
        update();
      } else {
        state.isInputPassword = true;
        update();
      }
    });
    userNameFocusNode.addListener(() {
      if (userNameFocusNode.hasFocus) {
        state.isInputPassword = false;
        update();
      } else {
        state.isInputPassword = true;
        update();
      }
    });
    passwordFocusNode.addListener(() {
      if (passwordFocusNode.hasFocus) {
        state.isInputPassword = true;
        update();
      } else {
        state.isInputPassword = false;
        update();
      }
    });
  }

  void startTimer(int seconds) {
    //设置 1 秒回调一次
    const period = Duration(seconds: 1);
    _timer = Timer.periodic(period, (timer) {
      //秒数减一，因为一秒回调一次
      seconds--;
      state.codeSeconds = seconds;
      if (seconds == 0) {
        //倒计时秒数为0，取消定时器
        cancelTimer();
      }
      update();
    });
  }

  //清除定时器
  void cancelTimer() {
    if (_timer != null){
      _timer?.cancel();
    }
  }

  ///发送短信验证码
  void getSmsCode() async {
    //清除焦点
    clearFocus();
    //先清除输入框
    clearVerifyCode();
    if (state.userNameText.isEmpty) {
      EasyLoading.showToast("请输入手机号码");
      return;
    }
    //显示loading
    await EasyLoading.show(
      status: '加载中...',
      maskType: EasyLoadingMaskType.black,
    );
    //先进行验证 然后发送短信验证码
    sendSmsCode(state.userNameText).then((result) {
      int? resultCode = result?.code;
      String? resultMsg = result?.msg;
      if (resultCode == ResponesCode.successCode) {
        int seconds = result?.data;
        EasyLoading.showToast("发送成功!");
        startTimer(seconds);
      } else {
        EasyLoading.showToast("发送失败: $resultMsg");
      }
    });
  }

  checkLoginParam(isSmsLogin) {
    if (state.userNameText.isEmpty) {
      EasyLoading.showToast("请输入登录账号", maskType: EasyLoadingMaskType.clear);
      return false;
    }
    if (isSmsLogin == true) {
      if (state.verifyText.isEmpty) {
        EasyLoading.showToast("请输入短信验证码", maskType: EasyLoadingMaskType.clear);
        return false;
      }
    } else {
      if (state.passwordText.isEmpty) {
        EasyLoading.showToast("请输入登录密码", maskType: EasyLoadingMaskType.clear);
        return false;
      }
    }
    return true;
  }

  //账号登录
  void loginByAccount() async {
    //显示loading
    await EasyLoading.show(
      status: '加载中...',
      maskType: EasyLoadingMaskType.black,
    );
    //参数
    Map<String, dynamic> params = {
      "account": state.userNameText,
      "password": CommonUtil.generateMd5(state.passwordText)
    };
    accountLogin(state.userNameText, CommonUtil.generateMd5(state.passwordText)).then((result) {
      if (result is LoginUser) {
        EasyLoading.showToast("登录成功!");
        //设置用户缓存
        setUserCache(result);
        //进入登录页面
        Future.delayed(const Duration(seconds: 1)).whenComplete(() {
          Get.offAllNamed(AppRoutes.homePage);
        });
      } else {
        clearVerifyCode();
        String? resultMsg = result?.msg;
        EasyLoading.showToast("登录失败: $resultMsg");
      }
    });
  }

  //验证码登录
  void loginBySmsCode() async {
    //显示loading
    await EasyLoading.show(
      status: '加载中...',
      maskType: EasyLoadingMaskType.black,
    );
    //处理参数
    Map<String, dynamic> params = {"mobile": state.userNameText, "smsCode": state.verifyText};
    //发送请求
    smsCodeLogin(state.userNameText, state.verifyText).then((result) {
      if (result is LoginUser) {
        EasyLoading.showToast("登录成功!");
        //设置用户缓存
        setUserCache(result);
        //进入首页
        Future.delayed(const Duration(seconds: 1)).whenComplete(() {
          Get.offAllNamed(AppRoutes.homePage);
        });
      } else {
        LogUtil.e(result, tag: "返回数据");
        clearVerifyCode();
        String? resultMsg = result?.msg;
        EasyLoading.showToast("登录失败: $resultMsg");
      }
    });
  }

  ///设置用户缓存
  void setUserCache(LoginUser user) {
    LogUtil.e(user, tag: "设置缓存");

    ///缓存登录信息
    LoginParams? params = user.params;

    ///设置token
    if (params?.token != null) {
      LogUtil.e("登录Token:[${params?.token}]设置成功!");
      CommonUtil.setLoginToken(params!.token!);
    }

    ///记住密码
    if (state.isRemeberMe) {
      StorageService.to.setBool(STORAGE_REMEMBER_ME_KEY, state.isRemeberMe);
      StorageService.to.setString(STORAGE_USER_PASSWORD_KEY, state.passwordText);
    }

    ///设置用户ID
    StorageService.to.setString(STORAGE_USER_ID_KEY, user.id.toString());
    LogUtil.e("用户ID缓存成功!");

    ///设置用户账号
    if (user.loginAccount != null) {
      StorageService.to.setString(STORAGE_USER_ACCOUNT_KEY, user.loginAccount!);
    }
    LogUtil.e("用户账号缓存成功!");
  }
}
